/**
 * @BelongsProject : LeetCode
 * @Author : WXY
 * @CreateTime : 2022-12-08  18:30
 * @Description :剑指 Offer 22. 链表中倒数第k个节点
 * @Version : 1.0
 */

public class Num022_getKthFromEnd {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }


    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode fast = head;
        ListNode slow = head;
        //快指针先走一个差值，
        while (k != 0) {
            fast = fast.next;
            k--;
        }
        //当快指针走到最后了，慢指针就是倒数第k个
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }


}
